package cn.exrick.xboot.modules.assessment.serviceimpl;

import cn.exrick.xboot.common.utils.ResultUtil;
import cn.exrick.xboot.common.vo.Result;
import cn.exrick.xboot.modules.assessment.dao.HkAssessmentIndexDao;
import cn.exrick.xboot.modules.assessment.entity.HkAssessmentIndex;
import cn.exrick.xboot.modules.assessment.entity.HkIndexClassify;
import cn.exrick.xboot.modules.assessment.service.HkAssessmentIndexService;
import cn.exrick.xboot.modules.assessment.vo.HkAssessmentIndexVo;
import cn.exrick.xboot.modules.assessment.vo.HkAssessmentInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.record.PageBreakRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.exrick.xboot.common.vo.SearchVo;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.lang.Nullable;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.Date;
import java.lang.reflect.Field;
import java.util.Optional;

import static com.alibaba.druid.sql.parser.Token.REPLACE;

/**
 * 考核指标接口实现
 * @author yck
 */
@Slf4j
@Service
@Transactional
public class HkAssessmentIndexServiceImpl implements HkAssessmentIndexService {

    @Autowired
    private HkAssessmentIndexDao hkAssessmentIndexDao;
    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public HkAssessmentIndexDao getRepository() {
        return hkAssessmentIndexDao;
    }

    @Override
    public Page<HkAssessmentIndex> findByCondition(HkAssessmentIndex hkAssessmentIndex, SearchVo searchVo, Pageable pageable) {

        return hkAssessmentIndexDao.findAll(new Specification<HkAssessmentIndex>() {
            @Nullable
            @Override
            public Predicate toPredicate(Root<HkAssessmentIndex> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {

                // TODO 可添加你的其他搜索过滤条件 默认已有创建时间过滤
                Path<Date> createTimeField = root.get("createTime");

                List<Predicate> list = new ArrayList<Predicate>();

                Path<String> indexName = root.get("indexName");
                if( StrUtil.isNotBlank(hkAssessmentIndex.getIndexName())){
                    list.add(cb.like(indexName,'%'+hkAssessmentIndex.getIndexName()+'%'));
                }
                Path<String> indexClassifyId = root.get("indexClassifyId");
                if( StrUtil.isNotBlank(hkAssessmentIndex.getIndexClassifyId())){
                    list.add(cb.equal(indexClassifyId,hkAssessmentIndex.getIndexClassifyId()));
                }
                Path<String> hontPostId = root.get("hontPostId");
                if( StrUtil.isNotBlank(hkAssessmentIndex.getHontPostId())){
                    list.add(cb.equal(hontPostId,hkAssessmentIndex.getHontPostId()));
                }
                Path<Integer> indexType = root.get("indexType");
                if( hkAssessmentIndex.getIndexType() != null){
                    list.add(cb.equal(indexType,hkAssessmentIndex.getIndexType()));
                }
                // 创建时间
                if(StrUtil.isNotBlank(searchVo.getStartDate())&&StrUtil.isNotBlank(searchVo.getEndDate())){
                    Date start = DateUtil.parse(searchVo.getStartDate());
                    Date end = DateUtil.parse(searchVo.getEndDate());
                    list.add(cb.between(createTimeField, start, DateUtil.endOfDay(end)));
                }

                Predicate[] arr = new Predicate[list.size()];
                cq.where(list.toArray(arr));
                return null;
            }
        }, pageable);
    }

    @Override
    public Result<Object> saveHkAssessmentIndex(HkAssessmentIndex hkAssessmentIndex){
        HkAssessmentIndex byIndexName = hkAssessmentIndexDao.findByIndexName(hkAssessmentIndex.getIndexName());
        if (byIndexName != null){
            return ResultUtil.error("该指标项名称已存在");
        }
        hkAssessmentIndexDao.save(hkAssessmentIndex);
        return ResultUtil.success("添加成功");
    }

    @Override
    public Result<Object> updateHkAssessmentIndex(HkAssessmentIndex hkAssessmentIndex){
        HkAssessmentIndex byIndexId = hkAssessmentIndexDao.getOne(hkAssessmentIndex.getId());
        if (byIndexId.getIndexName().equals(hkAssessmentIndex.getIndexName())){

        }else {
            HkAssessmentIndex byIndexName = hkAssessmentIndexDao.findByIndexName(hkAssessmentIndex.getIndexName());
            if (byIndexName!= null){
                return ResultUtil.error("指标项名称已存在");
            }
        }
        if (StringUtils.isBlank(hkAssessmentIndex.getId())){
            return ResultUtil.error("未找到指标项");
        }
        hkAssessmentIndexDao.saveAndFlush(hkAssessmentIndex);
        return ResultUtil.success("修改成功");
    }

    @Override
    public List<HkAssessmentInfoVo> findByFormEntityIdAndIndexType(String formEntityId, Integer indexId) {
        return hkAssessmentIndexDao.findByFormEntityIdAndIndexType(formEntityId,indexId);
    }

    public int batchInsert(List<HkAssessmentIndexVo> hkAssessmentIndices) {
        StringBuilder sb = new StringBuilder();
        sb.append("INSERT INTO hk_assessment_index(id,index_name, index_describe, index_type, index_score, index_classify_id, index_classify_name, hont_post_id, hont_post_name, create_time) VALUES ");
        for(HkAssessmentIndexVo hkAssessmentIndex : hkAssessmentIndices) {
            sb.append("(REPLACE(UUID(),\"-\",\"\"),?, ?, ?, ?, ?, ?, ?, ?, now()),");
        }
        String sql = sb.toString().substring(0, sb.length() - 1);
        log.info("sql",sql);
        Query query = entityManager.createNativeQuery(sql);
        int paramIndex = 1;
        for(HkAssessmentIndexVo hkAssessmentIndex : hkAssessmentIndices) {
            query.setParameter(paramIndex++, hkAssessmentIndex.getIndexName());
            query.setParameter(paramIndex++, hkAssessmentIndex.getIndexDescribe());
            query.setParameter(paramIndex++, hkAssessmentIndex.getIndexType());
            query.setParameter(paramIndex++, hkAssessmentIndex.getIndexScore());
            query.setParameter(paramIndex++, hkAssessmentIndex.getIndexClassifyId());
            query.setParameter(paramIndex++, hkAssessmentIndex.getIndexClassifyName());
            query.setParameter(paramIndex++, hkAssessmentIndex.getHontPostId());
            query.setParameter(paramIndex++, hkAssessmentIndex.getHontPostName());
        }
        return query.executeUpdate();
    }

    @Override
    public HkAssessmentIndex findByIndexName(String indexName) {
        return  hkAssessmentIndexDao.findByIndexName(indexName);
    }



}